package com.redwine.app.view;

import android.animation.ValueAnimator;
import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ListView;
import android.widget.TextView;

import com.ant.liao.GifView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.redwine.app.R;
import com.redwine.app.utils.EvaluateUtil;
import com.redwine.app.utils.NetUtil;
import com.redwine.app.utils.Utils;


public class RefreshListView extends ListView {

    private int downY = -1;// 手指按下时的Y值
    private int headerHeight;
    private View header;


    private static final int PULLDOWN_STATE = 0;// 下拉刷新
    private static final int RELEASE_STATE = 1;// 松开刷新
    private static final int REFRESHING_STATE = 2;// 正在刷新
    private int current_state = PULLDOWN_STATE;// 当前状态，默认是下拉刷新

    @ViewInject(R.id.iv_refreshheader)
    private GifView iv_refreshheader;// 下拉刷新gif动画

    @ViewInject(R.id.iv_refreshfooter)
    private GifView iv_refreshfooter;// 上拉加载gif动画

    //	@ViewInject(R.id.pb_refreshheader_progress)
    //	private ProgressBar pb_refreshheader_progress;// 进度条
    //
    @ViewInject(R.id.tv_refreshheader_state)
    private TextView tv_refreshheader_state;// 状态
    //
    //	@ViewInject(R.id.tv_refreshheader_time)
    //	private TextView tv_refreshheader_time;// 更新时间
    private RotateAnimation up;
    private RotateAnimation down;
    private OnRefreshingListener mListener;// 记录外界传递进来的监听器

    private View footer;
    private int footerHeight;
    private Activity mContext;




    public ScrollListViewListener mRefreshListViewListener;
    public interface ScrollListViewListener{
        void toScrollImg(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount);
    }

    public void setRefreshListViewListener(ScrollListViewListener refreshListViewListener){
        this.mRefreshListViewListener=refreshListViewListener;
    }

    public RefreshListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = (Activity) context;
        initHeader();
        initFooter();
        initAnimation();
    }

    private void initFooter() {
        footer = View.inflate(getContext(), R.layout.refresh_footer, null);
        ViewUtils.inject(this, footer);
        iv_refreshfooter.setGifImage(R.drawable.shuaxin_header);
        // 隐藏脚布局
        footer.measure(0, 0);
        footerHeight = footer.getMeasuredHeight();
        footer.setPadding(0, -footerHeight, 0, 0);
        this.addFooterView(footer);
        // 监听Listview的滚动状态
        this.setOnScrollListener(new MyOnScrollListener());
    }
    private void initAnimation() {
        up = new RotateAnimation(0, -180, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        up.setDuration(500);
        up.setFillAfter(true);

        down = new RotateAnimation(-180, -360, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        down.setDuration(500);
        down.setFillAfter(true);
    }

    private void initHeader() {
        header = View.inflate(getContext(), R.layout.refresh_header, null);
        ViewUtils.inject(this, header);
        // 隐藏头布局
        // 测量头布局
        iv_refreshheader.setGifImage(R.drawable.shuaxin_header);
        header.measure(0, 0);
        headerHeight = header.getMeasuredHeight();
        header.setPadding(0, -headerHeight, 0, 0);
        iv_refreshheader.setVisibility(View.GONE);
        this.addHeaderView(header);
    }
    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                downY = (int) ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                if (getFirstVisiblePosition() != 0) {
                    break;
                }
                if (downY == -1) {
                    downY = (int) ev.getY();
                }
                int moveY = (int) ev.getY();
                // 手指移动的距离
                int diffY = moveY - downY;
                if (diffY > 0) {
//                    mRefreshListenerImg.setIsChage(false);
                    // 下拉刷新头的topPadding值 = 手指移动的距离 - 下拉头的高度
                    int topPadding = (diffY - headerHeight) / 4;
                    // 根据下拉头布局是否完全展示，设置状态， topPadding = 0 是完全展示
                    if (topPadding >= 0 && current_state != RELEASE_STATE) {
                        current_state = RELEASE_STATE;
                        System.out.println("切换到松开刷新");
                        changeState(current_state);
                    } else if (topPadding < 0 && current_state != PULLDOWN_STATE) {
                        current_state = PULLDOWN_STATE;
                        System.out.println("切换到下拉刷新");
                        changeState(current_state);
                        header.setPadding(0, topPadding, 0, 0);
                    }
                    return true;// 自己消费事件
                }else{
                }
                break;
            case MotionEvent.ACTION_UP:
                if (downY == -1) {
                    downY = (int) ev.getY();
                }
                int moveUpY = (int) ev.getY();
                int diffUpY = moveUpY - downY;
                final int topPadding = (diffUpY - headerHeight) / 4;
                // 手指松开时，根据当前状态判断是否切换到正在刷新
                if (current_state == PULLDOWN_STATE) {
                    // 直接隐藏头布局
                    header.setPadding(0, -headerHeight, 0, 0);
                } else if (current_state == RELEASE_STATE) {
                    current_state = REFRESHING_STATE;
                    changeState(current_state);
                    System.out.println("切换到正在刷新");
                    // 模拟了一个值改变的"动画"
                    ValueAnimator animator = ValueAnimator.ofFloat(1.0f);
                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                        @Override
                        public void onAnimationUpdate(ValueAnimator animation) {
                            float percent = animation.getAnimatedFraction();
                            Integer height = EvaluateUtil.evaluateInt(percent, topPadding, 0);
                            // 直接隐藏头布局
                            header.setPadding(0, height, 0, 0);
                        }
                    });
                    animator.setDuration(500);
                    animator.start();
                    // 让头布局弹到正好完全展示
                    //                    header.setPadding(0, 0, 0, 0);
                    // 调用外界监听器的具体实现方法
                    if (mListener != null) {
                        mListener.onRefreshing();
                    }
                    downY = -1;
                }
                break;

            default:
                break;
        }
        return super.onTouchEvent(ev);
    }

    private void changeState(int currentState) {
        switch (currentState) {
            case PULLDOWN_STATE:
                tv_refreshheader_state.setText("");
                iv_refreshheader.setVisibility(View.VISIBLE);
                break;
            case RELEASE_STATE:
                tv_refreshheader_state.setText("");
                iv_refreshheader.setVisibility(View.VISIBLE);
                break;
            case REFRESHING_STATE:
                tv_refreshheader_state.setText("");
                iv_refreshheader.setVisibility(View.VISIBLE);
                break;

            default:
                break;
        }
    }

    // 定义下拉刷新接口，让外界实现具体的业务
    public interface OnRefreshingListener {
        // 下拉刷新方法
        void onRefreshing();

        // 加载更多方法
        void onLoadingMore();

        void onScrollY(int offsetY, int firstVisableItem);
    }

    public void setOnRefreshingListener(OnRefreshingListener listener) {
        this.mListener = listener;
    }

    // 提供刷新完成时，恢复状态的方法
    public void refreshFinished(boolean success) {
        if (success) {
            new Thread() {
                public void run() {
                    try {
                        Thread.sleep(1000);
                        Utils.runOnUIThread(new Runnable() {
                            @Override
                            public void run() {
                                tv_refreshheader_state.setText("");
                                iv_refreshheader.setVisibility(View.VISIBLE);
                                iv_refreshfooter.setVisibility(GONE);
                                if (0 == header.getPaddingTop()) {
                                    ValueAnimator animator = ValueAnimator.ofFloat(1.0f);
                                    animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                                        @Override
                                        public void onAnimationUpdate(ValueAnimator animation) {
                                            float percent = animation.getAnimatedFraction();
                                            Integer height = EvaluateUtil.evaluateInt(percent, 0, -headerHeight);
                                            // 直接隐藏头布局
                                            header.setPadding(0, height, 0, 0);

                                        }
                                    });
                                    animator.setDuration(200);
                                    animator.start();
                                }
                                // 模拟了一个值改变的"动画"
                                iv_refreshheader.setVisibility(View.GONE);
                                current_state = PULLDOWN_STATE;
                                tv_refreshheader_state.setText("");
                            }
                        });
                    } catch (InterruptedException e) {
                    }
                }
            }.start();
        } else {
            if (!NetUtil.isNetworkConnected(mContext)) {
                Utils.showToast(R.string.generic_check);
            } else {
                Utils.showToast(R.string.generic_check_online);
            }
        }
    }
    public void loadMoreFinished() {
        isLoadMore = false;
        iv_refreshfooter.setVisibility(VISIBLE);
        footer.setPadding(0, -footerHeight, 0, 0);
    }

    private boolean isLoadMore = false;// 当前是否正在加载更多
    private boolean scrollFlag = false;// 标记是否滑动
    private int startScrollPosition;// 标记上次滑动位置

    class MyOnScrollListener implements OnScrollListener {
        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // 监听停止和惯性停止状态
            if (OnScrollListener.SCROLL_STATE_FLING == scrollState || OnScrollListener.SCROLL_STATE_IDLE == scrollState) {
                // 是否当前界面显示的最后一条数据是Adapter中的最后一条
                if (getLastVisiblePosition() == getCount() - 1 && !isLoadMore) {
                    isLoadMore = true;
                    // 加载更多
                    footer.setPadding(0, 0, 0, 0);
                    // 让加载更多布局自动显示
                    setSelection(getCount());
                    //  调用外界加载更多的业务
                    if (mListener != null) {
                        mListener.onLoadingMore();
                    }
                }
            }
            if (scrollState == OnScrollListener.SCROLL_STATE_TOUCH_SCROLL) {
                scrollFlag = true;
                try {
                    startScrollPosition = view.getChildAt(0).getTop();
                } catch (Exception e) {

                }
            } else if (scrollState == OnScrollListener.SCROLL_STATE_FLING) {
                scrollFlag = true;
            } else {
                scrollFlag = false;
                startScrollPosition = 0;
            }
        }
        int a[]={3,4,6};
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {


            if(mRefreshListViewListener!=null){
                mRefreshListViewListener.toScrollImg(view,firstVisibleItem,visibleItemCount,totalItemCount);
            }
        }
    }
}
